<script setup>
import { isEqual } from 'lodash'
import cloneDeep from 'lodash/cloneDeep'
import { Content } from 'ant-design-vue/es/layout/layout'
import { reactive, ref, onMounted } from 'vue'
import TrialModal from './component/TrialModal.vue'
import SuspendModal from './component/SuspendModal.vue'
import { useAccountStore } from '@/stores/account'

import {
  Layout,
  message,
  Card as ACard,
  Table as ATable,
  Button as AButton,
  Select as ASelect,
  InputNumber as AInputNumber,
  Input as AInput,
  DatePicker as ADatePicker,
  Modal
} from 'ant-design-vue'
/**
 * ant-design-vue将英文改为中文 DatePicker日期控件
 * https://blog.csdn.net/qq2754289818/article/details/130972771
 */
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN'
dayjs.locale('zh-cn')
import {
  fetchGroupData,
  fetchPersonData,
  saveGroupData,
  preserSave,
  fetchLevelList
} from '@/api/claim'

const dateFormat = 'YYYY-MM-DD'
const pageConfig = {
  current: 1,
  pageSize: 15,
  defaultPageSize: 15,
  pageSizeOptions: ['15', '30', '50', '100'],
  showSizeChanger: true,
  total: 0,
  onChange: handlePageChange,
  hideOnSinglePage: true
}
let cacheObj = {}
function initData() {
  groupData.value = []
  state.selectedRowKeys = []
  initPersonData()
  getGroupData()
}
function initPersonData() {
  cacheObj = {}
  personData.value = []
  clonePersonData.value = []
  personState.selectedRowKeys = []
  pagination.value.current = 1
}
// 获取等级列表
const options = ref([])
async function getLevelList() {
  let res = null
  try {
    res = await fetchLevelList()
  } catch (err) {
    console.log('err', err)
  }
  if (res?.success == '0') {
    const list = res.data
    options.value = list
  }
}
const filterOption = (input, option) => {
  return option.value.toLowerCase().indexOf(input.toLowerCase()) >= 0
}

onMounted(() => {
  const accountStore = useAccountStore()
  getLevelList()
  accountStore.getSeqNo().then((data) => {
    getGroupData()
  })
  console.log(`the component is now mounted.`)
})
const columns = [
  {
    title: '序号',
    width: 70,
    dataIndex: 'Index',
    customRender: ({ text, record, index }) => `${index + 1}`
  },
  {
    title: '组名',
    width: 120,
    dataIndex: 'groupName'
  },
  {
    title: 'MGU/TPA',
    width: 80,
    dataIndex: 'dealCaseType'
  },
  {
    title: '付款对象',
    width: 68,
    dataIndex: 'dealRegistryType'
  },
  {
    title: '分配案件收到日期起期',
    width: 150,
    dataIndex: 'caseAssReceiveDateStart'
  },
  {
    title: '待分配理赔数',
    width: 120,
    dataIndex: 'toDistributedCount'
  },
  {
    title: '不参与分配数',
    width: 120,
    dataIndex: 'distributedCount'
  },
  {
    title: '组产能',
    width: 80,
    dataIndex: 'count'
  },
  {
    title: '试算分配理赔数',
    width: 120,
    dataIndex: 'tryDistributedCount'
  },
  {
    title: '试算分配溢出率',
    width: 120,
    dataIndex: 'tryDistributedChance'
  },
  {
    title: '实际分配理赔数',
    width: 120,
    dataIndex: 'isDistributedCount'
  },
  {
    title: '实际分配溢出率',
    width: 120,
    dataIndex: 'isDistributedChance'
  }
]
let groupData = ref([])
const state = reactive({
  selectedRowKeys: [], // Check here to configure the default column
  loading: false,
  buttonLoading: false
})
async function getGroupData() {
  state.loading = true
  let res = null
  try {
    res = await fetchGroupData()
  } catch (err) {
    console.log('err', err)
  } finally {
    state.loading = false
  }
  if (res?.success == '0') {
    const list = res.data.list
    groupData.value = list
  }
}
const onSelectChange = (selectedRowKeys) => {
  console.log('selectedRowKeys changed: ', selectedRowKeys)
  state.selectedRowKeys = selectedRowKeys
  initPersonData()
  if (selectedRowKeys.length > 0) {
    getPersonData(selectedRowKeys)
  }
}
// saveGroup info
async function saveGroup() {
  state.buttonLoading = true
  let res = null
  const list = groupData.value.map(({ groupName, groupNo, caseAssReceiveDateStart }) => {
    return {
      groupName,
      groupNo,
      caseAssReceiveDateStart
    }
  })
  console.log('list', list)
  const data = {
    list: list
  }
  try {
    res = await saveGroupData(data)
  } catch (err) {
    console.log('err', err)
  } finally {
    state.buttonLoading = false
  }
  if (res?.success == '0') {
    message.success('保存成功')
    initData()
  }
}

// 组成员
const columnsPerson = [
  {
    title: '序号',
    width: 70,
    dataIndex: 'Index',
    customRender: ({ text, record, index }) => `${index + 1}`
  },
  {
    title: '组名',
    width: 140,
    dataIndex: 'groupName'
  },
  {
    title: '核赔人',
    width: 140,
    dataIndex: 'operatorName'
  },
  {
    title: '等级',
    width: 140,
    dataIndex: 'kpiLevel'
  },
  {
    title: '标准产量',
    width: 140,
    dataIndex: 'averageCaseCapacity'
  },

  {
    title: '分配理赔数',
    minWidth: 140,
    width: 140,
    dataIndex: 'factor'
  },
  {
    title: '个人池理赔数',
    dataIndex: 'poolCount',
    width: 140
  },
  {
    title: '子任务',
    width: 120,
    dataIndex: 'subCount'
  },
  {
    title: '试算分配理赔数',
    width: 160,
    dataIndex: 'tryDistributedCount'
  },
  {
    title: '试算分配溢出率',
    dataIndex: 'tryDistributedChance',
    width: 160
  },
  {
    title: '实际分配理赔数',
    dataIndex: 'isDistributedCount',
    width: 160
  },
  {
    title: '实际分配溢出率',
    width: 160,
    dataIndex: 'isDistributedChance'
  }
]
const personState = reactive({
  selectedRowKeys: [], // Check here to configure the default column
  loading: false,
  buttonLoading: false
})
const pagination = ref(pageConfig)
function handlePageChange(page, pageSize) {
  console.log(page)
  console.log(pageSize)
  const isEqualData = isEqual(personData.value, clonePersonData.value)
  if (!isEqualData) {
    Modal.confirm({
      title: '提示',
      content: '当前页面存在更新未保存，请问是否保存并跳转？',
      okText: '确认',
      cancelText: '取消',
      async onOk() {
        await savePerson()
        pagination.value.current = page
        pagination.value.pageSize = pageSize
        getPersonData()
      },
      onCancel() {}
    })
  } else {
    pagination.value.current = page
    pagination.value.pageSize = pageSize
    getPersonData()
  }

  console.log(pagination.value, 'pagination')
}

const personData = ref([])
const clonePersonData = ref([])
async function getPersonData() {
  personState.loading = true
  let res = null
  const data = {
    pageNum: pagination.value.current,
    pageSize: pagination.value.pageSize,
    list: state.selectedRowKeys
  }
  try {
    res = await fetchPersonData(data)
  } catch (err) {
  } finally {
    personState.loading = false
  }
  if (res?.success == '0') {
    const data = res.data.list
    pagination.value.total = res.data.total
    personData.value = cloneDeep(data)
    clonePersonData.value = cloneDeep(data)
  }
}
const onSelectPersonChange = (selectedRowKeys, selectedRows) => {
  personState.selectedRowKeys = selectedRowKeys
  for (let i = 0; i < selectedRows.length; i++) {
    const item = selectedRows[i]
    const operatorId = item.operatorId
    cacheObj[operatorId] = item
  }
  console.log('cacheObj', cacheObj)
}

function numChange(val, record, key) {
  if (!val) {
    record[key] = 1
  }
}
async function savePerson() {
  personState.buttonLoading = true
  let res = null
  const list = personData.value.map(
    ({ groupNo, operatorId, kpiLevel, averageCaseCapacity, factor }) => {
      return {
        operatorId,
        kpiLevel,
        factor,
        averageCaseCapacity,
        groupNo: groupNo
      }
    }
  )
  const data = {
    list: list
  }
  try {
    res = await preserSave(data)
  } catch (err) {
    console.log('err', err)
  } finally {
    personState.buttonLoading = false
  }
  // 非阻断提示处理。
  if (res?.success == '0') {
    if (res.errorMsg) {
      message.info(res.errorMsg).then(() => {
        message.success('保存成功')
      })
    } else {
      message.success('保存成功')
    }
    clonePersonData.value = cloneDeep(personData.value)
  }
}
// 挂起设置-modal
const susPendVisible = ref(false)
function openSuspendModal() {
  susPendVisible.value = true
}
// 试算
const openTrialModal = ref(false)
const trialParams = reactive({
  trialCalculationDTOS: []
})
function trial() {
  const personSelectRowKeys = personState.selectedRowKeys
  const groupSeletcRowkeys = state.selectedRowKeys
  const groupArr = groupData.value.filter((item) => groupSeletcRowkeys.includes(item.groupNo))
  const selectList = []
  console.log('groupArr', groupArr)
  if (personSelectRowKeys.length == 0) {
    message.warning('请至少选中一条数据进行试算！')
    return
  }
  personSelectRowKeys.forEach((element) => {
    if (cacheObj[element]) {
      selectList.push(cacheObj[element])
    }
  })
  console.log('selectList', selectList)
  const trialCalculationDTOS = []
  groupArr.forEach(({ groupNo, caseAssReceiveDateStart }) => {
    let param = {
      assGroupNo: groupNo,
      receiveStartDate: caseAssReceiveDateStart,
      groupPersonId: []
    }
    selectList.forEach((item) => {
      if (item.groupNo == groupNo) {
        param.groupPersonId.push(item.operatorId)
      }
    })
    trialCalculationDTOS.push(param)
  })
  // 组装试算数据
  trialParams.trialCalculationDTOS = trialCalculationDTOS
  console.log('trialParams', trialParams)
  const isEqualData = isEqual(personData.value, clonePersonData.value)
  console.log(isEqualData, 'isEqualData')

  if (!isEqualData) {
    Modal.confirm({
      title: '提示',
      content: '页面信息有改动，请先保存再试算。否则按照默认分配数量进行分配。',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        openTrialModal.value = true
      },
      onCancel() {}
    })
  } else {
    openTrialModal.value = true
  }
}
function updateTable() {
  getPersonData()
  getGroupData()
}
</script>
<template>
  <Layout class="claim-layout">
    <Content>
      <div>
        <a-card :bordered="false">
          <p class="title">分组信息</p>
          <a-table
            :scroll="{ x: 1500 }"
            class="ant-table-striped"
            :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : null)"
            bordered
            size="small"
            :loading="state.loading"
            :data-source="groupData"
            :row-key="(record) => record.groupNo"
            :pagination="false"
            :row-selection="{ selectedRowKeys: state.selectedRowKeys, onChange: onSelectChange }"
            :columns="columns"
          >
            <template #bodyCell="{ column, text, record }">
              <template v-if="column.dataIndex === 'groupName'">
                <div class="editable-cell">
                  <a-input v-model:value="record.groupName" />
                </div>
              </template>
              <template v-if="column.dataIndex === 'caseAssReceiveDateStart'">
                <div class="editable-cell">
                  <a-date-picker
                    :locale="locale"
                    :format="dateFormat"
                    :valueFormat="dateFormat"
                    v-model:value="record.caseAssReceiveDateStart"
                  />
                </div>
              </template>
            </template>
          </a-table>
          <p class="group-btn" v-if="groupData.length > 0">
            <a-button type="primary" :loading="state.buttonLoading" @click="saveGroup"
              >保存</a-button
            >
            <a-button type="primary" @click="openSuspendModal">挂起设置</a-button>
          </p>
        </a-card>
        <a-card class="person-card">
          <p class="title">组内成员明细信息</p>
          <a-table
            class="ant-table-striped"
            :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : null)"
            bordered
            size="small"
            :scroll="{ x: 1500 }"
            :data-source="personData"
            :row-key="(record) => record.operatorId"
            :pagination="pagination"
            :loading="personState.loading"
            :row-selection="{
              selectedRowKeys: personState.selectedRowKeys,
              onChange: onSelectPersonChange
            }"
            :columns="columnsPerson"
          >
            <template #bodyCell="{ column, text, record }">
              <template v-if="column.dataIndex == 'kpiLevel'">
                <a-select
                  v-model:value="record.kpiLevel"
                  style="width: 100%"
                  placeholder="请选择"
                  :options="options"
                  :field-names="{ label: 'kpiLevel', value: 'factor' }"
                  :filter-option="filterOption"
                ></a-select>
              </template>
              <template v-if="column.dataIndex == 'averageCaseCapacity'">
                <a-input-number
                  id="averageCaseCapacity"
                  :precision="0"
                  @change="(val) => numChange(val, record, 'averageCaseCapacity')"
                  v-model:value="record.averageCaseCapacity"
                  :min="1"
                />
              </template>
              <template v-if="column.dataIndex == 'factor'">
                <a-input-number
                  id="inputNumber"
                  :precision="0"
                  @change="(val) => numChange(val, record, 'factor')"
                  v-model:value="record.factor"
                  :min="1"
                />
              </template>
            </template>
          </a-table>
          <p class="group-btn" v-if="personData.length > 0">
            <a-button type="primary" :loading="personState.buttonLoading" @click="savePerson"
              >保存</a-button
            >
            <a-button type="primary" @click="trial">试算</a-button>
          </p>
        </a-card>
        <TrialModal
          v-if="openTrialModal"
          :trial-params="trialParams"
          @update-refresh-table="initData()"
          @updateTable="updateTable()"
          @updateVisible="(visible) => (openTrialModal = visible)"
        ></TrialModal>
        <SuspendModal
          v-if="susPendVisible"
          :group-id-list="state.selectedRowKeys"
          v-model="susPendVisible"
        ></SuspendModal>
      </div>
    </Content>
  </Layout>
</template>
<style></style>
<style scoped lang="scss">
.ant-table-striped :deep(.table-striped) td {
  background-color: #fafafa;
}
.ant-table-striped :deep(.ant-table-thead) > tr > th {
  background-color: #fafafa;
}
.claim-layout {
  padding: 20px;
  background: #f5f5f5;
  .person-card {
    margin-top: 20px;
  }
  .title {
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 15px;
  }
  .group-btn {
    margin: 20px 0;
    .ant-btn {
      margin-right: 20px;
    }
  }
}
</style>
